package cn.cvs.service;

import cn.cvs.pojo.SysUser;
import cn.cvs.repository.UserRepository;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.Pageable;
import org.springframework.data.jpa.domain.Specification;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import javax.persistence.criteria.CriteriaBuilder;
import javax.persistence.criteria.CriteriaQuery;
import javax.persistence.criteria.Predicate;
import javax.persistence.criteria.Root;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;

@Service
public class SysUserServiceImpl implements SysUserService{

    @Resource
    UserRepository userRepository;
    @Override
    public String hello() {
        return "service---hello";
    }

    @Override
    public List<SysUser> findAll() {
        return userRepository.findAll();
    }

    @Override
    public List<SysUser> findByUsrNameAndUsrPassword(String usrName, String usrPassword) {
        return userRepository.findByUsrNameAndUsrPassword(usrName,usrPassword);
    }

    @Override
    public Long countByUsrName(String usrName) {
        return userRepository.countByUsrName(usrName);
    }

    @Override
    public List<SysUser> findByUsrNameLike(String usrName) {
        return userRepository.findByUsrNameLike(usrName);
    }

    @Override
    public List<SysUser> findByRoleId(Long roleId) {
        return userRepository.findByRoleId(roleId);
    }

    @Override
    public SysUser findByUsrId(Long usrId) {
        return userRepository.findByUsrId(usrId);
    }

    @Override
    public int modifyNameById(String usrName, Long usrId) {
        return userRepository.modifyNameById(usrName,usrId);
    }

    @Override
    public List<SysUser> findSysUsersByName(String usrName) {
        return userRepository.findSysUsersByName(usrName);
    }

    @Override
    public Page<SysUser> findPageByUsrRoleId(Long roleId, Pageable pageable) {
        return userRepository.findPageByUsrRoleId(roleId,pageable);
    }

    @Override
    public Page<SysUser> findPageByMap(Map params, Pageable pageable) {
        //自定义复杂查询,扩展specification接口
        return userRepository.findAll(new Specification<SysUser>() {
            @Override
            public Predicate toPredicate(Root<SysUser> root, CriteriaQuery<?> query, CriteriaBuilder criteriaBuilder) {

                List<Predicate> predicates = new ArrayList<>();
                if (null != params.get("usrName")){
                    predicates.add(criteriaBuilder.like(root.get("usrName"),"%"+params.get("usrName")+"%"));
                }

                if (null != params.get("roleId")){
                    predicates.add(criteriaBuilder.equal(root.get("usrRoleId"),params.get("roleId")));
                }
                return criteriaBuilder.and(predicates.toArray(new Predicate[predicates.size()]));
            }
        },pageable);
    }
}
